<?php

namespace api\controllers;

use common\models\Activity;
use common\helpers\predis\Predis;
use common\helpers\sms\Sms;
use common\models\Groupbuy;
use common\models\User;
use common\models\Product;
use common\service\ServiceFactory;
use Yii;
use yii\web\Controller;
use yii\web\ServerErrorHttpException;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public $enableCsrfValidation = false;

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }


    /**
     * OpenID 登陆
     * @return array
     */
    public function actionLoginWithOpenId()
  { //  return ['code' => 0, 'message' => $_POST];
        $openId = Yii::$app->request->post("open_id");
        if (empty($openId)) {
            return ['code' => 0, 'message' => 'openId为空'];
        }
        $user = User::find()->where(['open_id' => $openId])->one();
        if ($user != null) {
            $user->save();
            $user->token = User::refreshToken($user->phone, $user);
            return ['code' => 1, 'data' => $user];
        }

        try {
            $responseData = ServiceFactory::getInstance()->getUserService()->getUserByApi('', $openId, '');
            if (!empty($responseData)) {
                $responseData = $responseData[0];
                $user = new User();
                $user->customer_id = $responseData->customer_id;
                $user->open_id = $responseData->open_id;
                $user->nickname = $responseData->nickname;
                $user->avatar = $responseData->avatar;
                $user->status = $responseData->status;
                $user->phone = $responseData->phone;
                $user->created_at = $responseData->created_at;
                $user->updated_at = $responseData->updated_at;
                $user->save();
                $user->token = User::refreshToken($user->phone, $user);
                return ['code' => 1, 'data' => $user];
            }
            return ['code' => 0, 'message' => "未绑定手机号"];
        } catch (\Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }


    /**
     * App登陆
     * @return array
     * @throws ServerErrorHttpException
     */
    public function actionLoginByApp()
    {
        $customerId = Yii::$app->request->post('customer_id');
        $nickname = Yii::$app->request->post('nickname');
        $avatar = Yii::$app->request->post('avatar');
        $phone = Yii::$app->request->post('phone');
        if (empty($customerId) || empty($phone)) {
            return ['code' => 0, 'message' => 'customerId和手机号不能为空'];
        }
        $user = User::find()->where(['phone' => $phone])->one();
        if ($user != null) {
//            if (!empty($user->customer_id) && $user->customer_id != $customerId) {
//                return ['code' => -2, 'message' => "该手机号已绑定别的用户"];
//            }
            if (empty($user->customer_id)) {
                try {
                    $user = ServiceFactory::getInstance()->getUserService()->updateUser($phone, $customerId, "", $avatar, $nickname);
                    $user->token = User::refreshToken($phone, $user);
                    return ['code' => 1, 'data' => $user];
                } catch (\Exception $e) {
                    return ['code' => -1, 'message' => $e->getMessage()];
                }
            }
            //if ($user->customer_id == $customerId) {

//               $user->save();
               $user->token = User::refreshToken($phone, $user);
                return ['code' => 1, 'data' => $user];
            //}

        }

        try {
            $responseData = ServiceFactory::getInstance()->getUserService()->getUserByApi($phone, '', '');
            if (!empty($responseData)) {
                $responseData = $responseData[0];

                if (empty($responseData->customer_id)) {
                    $user = ServiceFactory::getInstance()->getUserService()->updateUser($phone, $customerId, "", $avatar, $nickname);
                    $u = new User();
                    $u->customer_id = $responseData->customer_id;
                    $u->phone=$phone;
                    $u->nickname=$nickname;
                    $u->avatar=$avatar;
                    $u->status=$responseData->status;
                    $u->save();
                    $user->token = User::refreshToken($phone, $u);

                    return ['code' => 1, 'data' => $user];
                } else {
                    $user = new User();
                    $user->customer_id = $responseData->customer_id;
                    $user->phone=$phone;
                    $user->nickname=$nickname;
                    $user->avatar=$avatar;
                    $user->status=$responseData->status;
                    $user->save();
                    $user->token = User::refreshToken($phone, $user);
                    return ['code' => 1, 'data' => $user];
//                    return ['code' => -2, 'message' => "该手机号已绑定别的用户"];
                }
            }

            $user = ServiceFactory::getInstance()->getUserService()->registerUser($phone, "", $customerId, $avatar, $nickname);
            $user->token = User::refreshToken($phone, $user);
            return ['code' => 1, 'data' => $user];
        } catch (\Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }


    /**
     * pc登陆 带验证码
     */
    public function actionLoginByPc()
    {
        $phone = Yii::$app->request->post("phone");
        $code = Yii::$app->request->post("code");
        if (empty($phone) || empty($code)) {
            return ['code' => 0, 'msg' => '手机号或验证码为空'];
        }

        $cacheKey = Sms::getCacheKey($phone);
        $originCode = Predis::getInstance()->getClient()->client->get($cacheKey);
        if ($code != $originCode) {
            return ['code' => 0, 'message' => '验证码错误'];
        }
        $user = User::find()->where(['phone' => $phone])->one();
        if ($user != null) {
            $user->token = User::refreshToken($phone, $user);
            $user->save();
            return ['code' => 1, 'data' => $user];
        }

        try {
            $responseData = ServiceFactory::getInstance()->getUserService()->getUserByApi($phone, '', '');
            if (!empty($responseData)) {
                $responseData = $responseData[0];
                $user = new User();
                $user->customer_id = $responseData->customer_id;
                $user->nickname = $responseData->nickname;
                $user->avatar = $responseData->avatar;
                $user->phone = $responseData->phone;
                $user->open_id = $responseData->open_id;
                $user->status = $responseData->status;
                $user->created_at = $responseData->created_at;
                $user->updated_at = $responseData->updated_at;
                $user->save();
                $user->token = User::refreshToken($phone, $user);
                return ['code' => 1, 'data' => $user];
            } else {
                $user = ServiceFactory::getInstance()->getUserService()->registerUser($phone, "", "", "", "");
                $user->token = User::refreshToken($phone, $user);
                return ['code' => 1, 'data' => $user];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }

    /**
     * 微信登陆带验证码
     */
    public function actionLoginByWeiChat()
    {
        $openId = Yii::$app->request->post("open_id");
        $nickname = Yii::$app->request->post("nickname");
        $code = Yii::$app->request->post("code");
        $phone = Yii::$app->request->post("phone");
        $avatar = Yii::$app->request->post("avatar");
        if (empty($phone) || empty($code) || empty($openId)) {
            return ['code' => 0, 'msg' => '手机号或验证码或openID为空'];
        }

        $cacheKey = Sms::getCacheKey($phone);
        $originCode = Predis::getInstance()->getClient()->client->get($cacheKey);
        if ($code != $originCode) {
            return ['code' => 0, 'message' => '验证码错误'];
        }

        $user = User::find()->where(['phone' => $phone])->one();
        if ($user != null) {
            if (!empty($user->open_id) && $user->open_id != $openId) {
                return ['code' => 0, 'message' => "该手机号已绑定别的用户"];
            }

            if ($user->open_id == $openId) {
                $user->save();
                $user->token = User::refreshToken($phone, $user);
                return ['code' => 1, 'data' => $user];
            }
            if (empty($user->open_id)) {
                try {
                    $user = ServiceFactory::getInstance()->getUserService()->updateUser($phone, "", $openId, $avatar, $nickname);
                    $user->token = User::refreshToken($phone, $user);
                    return ['code' => 1, 'data' => $user];
                } catch (\Exception $e) {
                    return ['code' => -1, 'message' => $e->getMessage()];
                }
            }
        }

        try {
            $responseData = ServiceFactory::getInstance()->getUserService()->getUserByApi($phone, '', '');
            if (!empty($responseData)) {
                $responseData = $responseData[0];
                if (empty($responseData->open_id)) {
                    $user = ServiceFactory::getInstance()->getUserService()->updateUser($phone, "", $openId, $avatar, $nickname);
                    $user->token = User::refreshToken($phone, $user);
                    return ['code' => 1, 'data' => $user];
                } elseif ($responseData->open_id == $openId) {
                    $user = new User();
                    $user->customer_id = $responseData->customer_id;
                    $user->nickname = $responseData->nickname;
                    $user->avatar = $responseData->avatar;
                    $user->phone = $responseData->phone;
                    $user->open_id = $responseData->open_id;
                    $user->status = $responseData->status;
                    $user->created_at = $responseData->created_at;
                    $user->updated_at = $responseData->updated_at;
                    $user->save();
                    $user->token = User::refreshToken($phone, $user);
                    return ['code' => 1, 'data' => $user];
                } else {
                    return ['code' => 0, 'message' => "该手机号已绑定别的用户"];
                }
            }

            $user = ServiceFactory::getInstance()->getUserService()->registerUser($phone, $openId, "", $avatar, $nickname);
            $user->token = User::refreshToken($phone, $user);
            return ['code' => 1, 'data' => $user];
        } catch (\Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }

    public function actionTest(){
//        $conn = Yii::$app->db;
//        $sql ="SELECT concat('DROP TABLE IF EXISTS ', table_name, ';')  sss FROM information_schema.tables WHERE table_schema = 'web';";
//        $commond = $conn->createCommand($sql);
//        $res=$commond->queryAll();
//
//        foreach($res as $sql){
//
//            var_dump($sql);
//            $commond = $conn->createCommand($sql['sss']);
//            $res=$commond->execute();
//        }


        echo Yii::$app->request->hostInfo;
    }

    public function actionGetindexinfo(){
        $activity_id=Yii::$app->request->post('activity_id');

        $infos = Activity::find()->where(['id'=>$activity_id])->select("id,name,banner,other_entry,other_entry_url,peoples,goods,description,store_id,status,share_title,share_img,share_remark,share_url")->asArray()->one();
        if(!empty($infos)){
            if($infos['status']!=1){
                return ['code'=>-1,'message'=>'活动已下架'];
            }
            $data=$infos;
            $goods = $data['goods'];
            $arr=explode(",",$goods);
            foreach($arr as $goodid){
                $good = Product::findOne($goodid);
                if($good){
                    $data['products'][]=$good->toArray();
                }

            }

            return ['code'=>1,'message'=>'success','data'=>$data];
        }else{
            return ['code'=>0,'message'=>'活动不存在'];
        }
    }
    //获取团购信息
    public function actionGetgroupbuy(){
        $group_id=Yii::$app->request->post('group_id');
            $activity_id=Yii::$app->request->post('activity_id');
            $activity=Activity::findOne($activity_id);
            if(empty($activity)){
                return ['code'=>-2,'message'=>'没有这个活动'];
            }
        $groupbuy = Groupbuy::findOne($group_id);
        if($groupbuy){
            $goodsid=$groupbuy->goodsid;
            $product=  Product::findOne($goodsid)->getattributes(explode(",","id,ttid,name,remark,notes,image,newprice,price,share_title,share_img,share_txt,share_url,description"));
            if($product){

                $data['id']=$groupbuy->id;
                $data['status']=$groupbuy->status;
                $data['peoples']=$activity->peoples;
                $data['product']=$product;
                $data['members']=json_decode($groupbuy->users,true);
                return ['code'=>1,'message'=>'success','data'=>$data];
            }else{
                return ['code'=>-1,'message'=>'数据错误'];
            }

        }else{
            return ['code'=>0,'message'=>'没有这个团'];
        }
    }

}
